package com.ruijie.acl.web.validator;

import java.util.Map;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

import org.apache.commons.lang.StringUtils;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.faces.Validator;

import com.ruijie.acl.Template;
import com.ruijie.acl.service.VariableService;
import com.ruijie.foundation.international.MessageSupport;
/**
 * <p>
 * Title: 变量名称验证
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * 	变量名称合法性验证
 * </p>
 * <p>
 * Copyright: Copyright (c) 2009
 * </p>
 * <p>
 * Company: Ruijie Co., Ltd.
 * </p>
 * <p>
 * Create Time: 2009-07-14
 * </p>
 * <p>
 * Update Time:
 * </p>
 * <p>
 * Updater:
 * </p>
 * <p>
 * Update Comments:
 * </p>
 * @author ASAI
 */
@Name("variableNameValidator")
@Validator
public class VariableNameValidator extends MessageSupport implements javax.faces.validator.Validator {
	
	@In private Map<String, String> messages;
	
	@In("#{variableService}")
	private VariableService variableService;
	/**
	 * 匹配英文字母、数字、下划线的正则表达式
	 */
	private Pattern pattern=Pattern.compile("[a-zA-Z0-9_]+");
	@Override
	public void validate(FacesContext context, UIComponent component, Object obj)
			throws ValidatorException {
		
		String value=obj.toString().trim();

		if(component.getAttributes().get("required").toString().equals("true")){
			if(!StringUtils.isNotEmpty(value.replaceAll("　",   " ").trim())){
				throw new ValidatorException(new FacesMessage(messages.get("javax.faces.component.UIInput.REQUIRED")));
			}
		}
		if(value.length()>15){
			throw new ValidatorException(new FacesMessage(getI18NMessage("acl_validator_template_var_name_max_length_15")));
		}
		if(!pattern.matcher(value).matches()){
			throw new ValidatorException(new FacesMessage(getI18NMessage("acl_validator_template_var_name_letters")));
		}
		Template template = (Template)component.getAttributes().get("template");
		Long variableId = (Long)component.getAttributes().get("variableId");
		if(variableService.isExistVariableName(value,template,variableId)){
			throw new ValidatorException(new FacesMessage(getI18NMessage("acl_validator_template_var_name_repeat")));
		}
	}

}
